<?php
/**
 * Created by PhpStorm.
 * User: wangkxin@foxmail.com
 * Date: 2022/7/7
 * Time: 15:23
 */

namespace app\index\controller;


use app\BaseController;
use app\Request;
use think\cache\driver\Redis;
use think\facade\Db;

/**
 *  并发处理解决超卖问题
 * 并发测试
 */
class BuyController extends BaseController
{

    /**
     * 没有加redis锁 会出现超卖情况
     */
   /* public function buy()
    {
        $storage = Db::table('storage')->find(1);
        $num = $storage['number'];
        if($num > 0){
             Db::table('order')->insert(['number'=>$num]);
             $insertId = Db::table('order')->getLastInsID();
             if($insertId){
                 Db::table('storage')
                     ->where('id',1)
                     ->dec('number',1)
                     ->update();
             }

        }
        return 'gfgf';
    }*/


    /**
     * 加入redis 锁
     * 阻止超卖情况
     */
    public function buy2(Request $request){
        $lockObj = Lock::getInstance();
        if($lock = $lockObj->set('storage',10)){
            $storage = Db::table('storage')->find(1);
            $num = $storage['number'];
            if($num > 0){
                Db::table('order')->insert(['number'=>$num]);
                $insertId = Db::table('order')->getLastInsID();
                if($insertId){
                    Db::table('storage')
                        ->where('id',1)
                        ->dec('number',1)
                        ->update();
                }

            }
            //解锁
            $lockObj->del('storage');
        }else{
            //加锁不成功执行其他操作
            return 'lock failed';
        }
        return 'gfgf';
    }






}